#include "../source/server.hpp"

// 管理的所有连接
std::unordered_map<uint64_t, Connection::ptr> _conns;
uint64_t conn_id = 0;
EventLoop base_loop;

LoopThreadPool *loop_pool;

void ConnectionDestory(const Connection::ptr &conn) {
    _conns.erase(conn->Id()); 
}

void OnConnected(const Connection::ptr &conn) {
    LOG(LogLevel::INFO) << "NEW CONNECTION: " << conn.get();
}

void OnMessage(const Connection::ptr &conn, Buffer* buf) {
    LOG(LogLevel::INFO) << buf->ReadPosition();
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello";
    conn->Send(str.c_str(), str.size());
    conn->Shutdown();       // 最后实际上是在handlewrite这里关闭连接的
}

void NewConnection(int fd)
{
    conn_id++;
    Connection::ptr conn(new Connection(loop_pool->NextLoop(), conn_id, fd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));         
    conn->SetServerClosedCallback(std::bind(ConnectionDestory, std::placeholders::_1));   
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));            
    conn->EnableInactiveRelease(10);                                // 启动非活跃销毁功能
    conn->Established();                                            // 就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
}

int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create(); 

    Accepter accepter(&base_loop, 8080);
    accepter.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));

    accepter.Listen();
    base_loop.Start();
    
    return 0;
}